package com.xym.search.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.xym.common.bean.EasyUiResult;
import com.xym.search.bean.Item;
import com.xym.search.service.SearchService;

@Controller
public class SearchController {

	@Autowired
	private SearchService searchService;
	private static final Integer PAGE_SIZE = 32;
	/**
	 * 搜索请求
	 * http://search.taotao.com/search?keyword={param}&page=1
	 * 同步请求
	 * 参数： 搜索参数
	 * 结果：query(查询参数),itemList(搜索的商品集合),page(页码),pages(总页数)
	 */
	 @RequestMapping(value="search",method=RequestMethod.GET)
	 public ModelAndView search(@RequestParam("q") String param,
			 @RequestParam(value="page",defaultValue="1") Integer pageNum){
		 ModelAndView mv = new ModelAndView("search");
		 try {
			 param = new String(param.getBytes("ISO-8859-1"), "UTF-8");
			 mv.addObject("query", param);
			 //搜索到的商品集合
			 EasyUiResult result = this.searchService.search(param,pageNum,PAGE_SIZE);
			 @SuppressWarnings("unchecked")
			List<Item> itemList = (List<Item>) result.getRows();
			 mv.addObject("itemList", itemList);
			 mv.addObject("page", pageNum);
			 //总页数 = 总记录数 % 每页显示条数 ?   总记录数 / 每页显示条数  : 总记录数 / 每页显示条数 + 1
			 Long total = result.getTotal();
			 Integer itemTotal = Integer.valueOf(total.toString());
			 Integer pages = itemTotal % PAGE_SIZE == 0 ? itemTotal / PAGE_SIZE : itemTotal / PAGE_SIZE + 1;
			 mv.addObject("pages", pages);
		} catch (Exception e) {
			e.printStackTrace();
		}
		 return mv;
	 }
	
}
